<template>
    <div class="employee-management">
      <!-- 页面头部 -->
      <div class="page-header">
        <h2>员工管理</h2>
        <div class="header-actions">
          <el-button type="primary" :icon="Plus" @click="handleAddEmployee">
            添加员工
          </el-button>
          <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
        </div>
      </div>
  
      <!-- 搜索和筛选 -->
      <el-card class="search-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="员工姓名">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入员工姓名"
              clearable
              @keyup.enter="handleSearch"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              v-model="searchForm.phone"
              placeholder="请输入联系电话"
              clearable
              @keyup.enter="handleSearch"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="员工状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option label="全部" value="" />
              <el-option label="在职" value="active" />
              <el-option label="离职" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间">
            <el-date-picker
              v-model="searchForm.hireTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 员工列表 -->
      <el-card class="employee-list-card">
        <template #header>
          <div class="card-header">
            <span>员工列表</span>
            <div class="search-stats">
              <span v-if="employeeList.length > 0" class="search-result-info">
                共找到 {{ pagination.total }} 条记录
              </span>
            </div>
            <div class="batch-actions">
              <el-button
                v-if="selectedEmployees.length > 0"
                type="danger"
                size="small"
                @click="handleBatchDelete"
              >
                批量删除 ({{ selectedEmployees.length }})
              </el-button>
              <el-button
                v-if="selectedEmployees.length > 0"
                type="warning"
                size="small"
                @click="handleBatchDeactivate"
              >
                批量离职 ({{ selectedEmployees.length }})
              </el-button>
            </div>
          </div>
        </template>
  
        <el-table
          :data="employeeList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          row-key="employeeId"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="employeeName" label="员工姓名" width="120" />
          <el-table-column prop="phone" label="联系电话" width="140" />
          <el-table-column prop="hireTime" label="入职时间" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.hireTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="employeeStatus" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.employeeStatus === 'active' ? 'success' : 'info'">
                {{ scope.row.employeeStatus === 'active' ? '在职' : '离职' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="workDuration" label="工作年限" width="100">
            <template #default="scope">
              {{ calculateWorkDuration(scope.row.hireTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="handleViewEmployee(scope.row)">
                  查看
                </el-button>
                <el-button size="small" type="info" @click="handleEditEmployee(scope.row)">
                  编辑
                </el-button>
                <el-button
                  size="small"
                  :type="scope.row.employeeStatus === 'active' ? 'warning' : 'success'"
                  @click="handleToggleStatus(scope.row)"
                >
                  {{ scope.row.employeeStatus === 'active' ? '离职' : '复职' }}
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeleteEmployee(scope.row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 员工编辑对话框 -->
      <EmployeeEditDialog
        v-model="employeeDialogVisible"
        :employee-data="currentEmployee"
        :enterprise-id="currentCompanyId"
        @success="handleEmployeeSuccess"
      />
  
      <!-- 确认操作对话框 -->
      <el-dialog
        v-model="confirmDialogVisible"
        :title="confirmDialogTitle"
        width="400px"
        :close-on-click-modal="false"
      >
        <div class="confirm-content">
          <div class="confirm-icon">
            <el-icon :size="48" :color="confirmDialogIconColor">
              <component :is="confirmDialogIcon" />
            </el-icon>
          </div>
          <div class="confirm-message">
            {{ confirmDialogMessage }}
          </div>
        </div>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleConfirmCancel">取消</el-button>
            <el-button
              :type="confirmDialogButtonType"
              :loading="confirmLoading"
              @click="handleConfirmOk"
            >
              {{ confirmDialogButtonText }}
            </el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 员工详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="员工详情"
        width="600px"
      >
        <div v-if="currentEmployee" class="employee-detail">
          <div class="employee-header">
            <h3>{{ currentEmployee.employeeName }}</h3>
            <el-tag :type="currentEmployee.employeeStatus === 'active' ? 'success' : 'info'">
              {{ currentEmployee.employeeStatus === 'active' ? '在职' : '离职' }}
            </el-tag>
          </div>
  
          <div class="employee-info">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <label>联系电话：</label>
                  <span>{{ currentEmployee.phone || '未设置' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <label>入职时间：</label>
                  <span>{{ formatDate(currentEmployee.hireTime) }}</span>
                </div>
              </el-col>
            </el-row>
  
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <label>工作年限：</label>
                  <span>{{ calculateWorkDuration(currentEmployee.hireTime) }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <label>员工状态：</label>
                  <span>{{ currentEmployee.employeeStatus === 'active' ? '在职' : '离职' }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
  
          <div class="employee-stats">
            <h4>工作统计</h4>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <span class="stat-label">工作天数</span>
                  <span class="stat-value">{{ calculateWorkDays(currentEmployee.hireTime) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <span class="stat-label">工作月数</span>
                  <span class="stat-value">{{ calculateWorkMonths(currentEmployee.hireTime) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <span class="stat-label">工作年数</span>
                  <span class="stat-value">{{ calculateWorkYears(currentEmployee.hireTime) }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useEnterpriseStore } from '@/store/job/modules/enterprise'
  import { employeeAPI, enterpriseAPI } from '@/api/enterprise'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Refresh, User, Warning, Delete, Check, OfficeBuilding } from '@element-plus/icons-vue'
  import EmployeeEditDialog from '@/components/job/EmployeeEditDialog.vue'
  
  const enterpriseStore = useEnterpriseStore()
  
  // 当前公司ID（固定为1）
  const currentCompanyId = ref(1)
  
  // 响应式数据
  const loading = ref(false)
  const submitting = ref(false)
  const employeeDialogVisible = ref(false)
  const detailDialogVisible = ref(false)
  const isEdit = ref(false)
  const selectedEmployees = ref([])
  const currentEmployee = ref(null)
  
  // 搜索表单
  const searchForm = reactive({
    keyword: '',
    phone: '',
    status: '',
    hireTimeRange: []
  })
  
  // 员工表单
  const employeeForm = reactive({
    employeeName: '',
    phone: '',
    hireTime: '',
    employeeStatus: 'active'
  })
  
  // 表单验证规则
  const employeeFormRules = {
    employeeName: [
      { required: true, message: '请输入员工姓名', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    hireTime: [
      { required: true, message: '请选择入职时间', trigger: 'change' }
    ]
  }
  
  // 分页数据
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })
  
  // 员工列表
  const employeeList = ref([])
  
  // 假设企业ID为1
  const enterpriseId = 1
  
  // 确认对话框相关数据
  const confirmDialogVisible = ref(false)
  const confirmDialogTitle = ref('')
  const confirmDialogMessage = ref('')
  const confirmDialogIcon = ref('')
  const confirmDialogIconColor = ref('')
  const confirmDialogButtonText = ref('')
  const confirmDialogButtonType = ref('')
  const confirmLoading = ref(false)
  const currentConfirmAction = ref('')
  const currentConfirmEmployee = ref(null)
  
  onMounted(async () => {
    try {
      console.log('员工管理页面开始初始化...')
      // 加载公司列表
      await loadCompanyList()
      console.log('公司列表加载完成，当前公司ID:', currentCompanyId.value)
      // 加载员工列表
      await loadEmployeeList()
      console.log('员工管理页面初始化完成，员工数量:', employeeList.value.length)
    } catch (error) {
      console.error('页面初始化失败:', error)
      ElMessage.error('页面初始化失败，请刷新页面重试')
    }
  })
  
  // 处理公司切换
  const handleCompanySwitch = async (newCompanyId) => {
    if (newCompanyId === currentCompanyId.value) {
      return
    }
    
    try {
      console.log('切换公司从', currentCompanyId.value, '到', newCompanyId)
      currentCompanyId.value = newCompanyId
      ElMessage.success(`已切换到：${currentCompanyName.value}`)
      
      // 重新加载当前公司的数据
      await loadCompanyData()
    } catch (error) {
      console.error('切换公司失败:', error)
      ElMessage.error('切换公司失败，请重试')
    }
  }
  
  // 加载公司数据
  const loadCompanyData = async () => {
    try {
      // 加载企业信息
      await enterpriseStore.fetchEnterpriseInfo(currentCompanyId.value)
      
      // 重新加载当前公司的员工数据
      await loadEmployeeList()
      
      console.log(`已加载公司 ${currentCompanyId.value} 的数据`)
    } catch (error) {
      console.error('加载公司数据失败:', error)
      ElMessage.error('加载公司数据失败')
    }
  }
  
  // 加载员工列表
  const loadEmployeeList = async () => {
    loading.value = true
    console.log('开始加载员工列表，当前公司ID:', currentCompanyId.value)
    
    try {
      // 直接从API加载员工数据
      console.log('调用API获取员工数据...')
      const result = await employeeAPI.getEnterpriseEmployees(currentCompanyId.value, {
        page: pagination.current,
        pageSize: pagination.pageSize,
        keyword: searchForm.keyword,
        phone: searchForm.phone,
        status: searchForm.status,
        hireTimeStart: searchForm.hireTimeRange && searchForm.hireTimeRange[0] ? searchForm.hireTimeRange[0] : '',
        hireTimeEnd: searchForm.hireTimeRange && searchForm.hireTimeRange[1] ? searchForm.hireTimeRange[1] : ''
      })
      
      console.log('API响应结果:', result)
      console.log('API响应类型:', typeof result)
      console.log('API响应键:', Object.keys(result || {}))
      
      // 处理API响应格式
      // 响应拦截器已经处理了code=0的情况，result就是完整的响应对象
      if (result && result.data && result.data.employees) {
        employeeList.value = result.data.employees || []
        pagination.total = result.data.pagination?.total || 0
        console.log('成功解析员工数据:', employeeList.value.length, '条记录')
        console.log('员工数据详情:', employeeList.value)
      } else {
        console.log('API响应格式不正确，result:', result)
        console.log('result.data:', result?.data)
        console.log('result.data.employees:', result?.data?.employees)
        employeeList.value = []
        pagination.total = 0
      }
      
      console.log(`从API加载公司 ${currentCompanyId.value} 的员工数据:`, employeeList.value.length, '条记录')
    } catch (error) {
      console.error('加载员工列表失败:', error)
      console.error('错误详情:', error.message)
      console.error('错误堆栈:', error.stack)
      
      // 如果API连接失败，使用模拟数据
      console.log('API连接失败，使用模拟数据')
      const mockEmployees = getMockEmployees(currentCompanyId.value)
      employeeList.value = mockEmployees
      pagination.total = mockEmployees.length
      
      ElMessage.warning('无法连接到服务器，显示模拟数据')
    } finally {
      loading.value = false
      console.log('员工列表加载完成，最终数据:', employeeList.value.length, '条记录')
    }
  }
  
  // 获取模拟员工数据
  const getMockEmployees = (enterpriseId) => {
    const mockData = {
      1: [
        {
          employeeId: 1,
          employeeName: '张三',
          phone: '13800138001',
          hireTime: '2024-01-15',
          employeeStatus: 'active',
          position: '前端开发工程师',
          department: '技术部'
        },
        {
          employeeId: 2,
          employeeName: '李四',
          phone: '13800138002',
          hireTime: '2024-01-20',
          employeeStatus: 'active',
          position: '后端开发工程师',
          department: '技术部'
        },
        {
          employeeId: 3,
          employeeName: '王五',
          phone: '13800138003',
          hireTime: '2024-02-01',
          employeeStatus: 'active',
          position: '产品经理',
          department: '产品部'
        }
      ],
      2: [
        {
          employeeId: 4,
          employeeName: '孙八',
          phone: '13800138006',
          hireTime: '2024-01-10',
          employeeStatus: 'active',
          position: 'Java后端工程师',
          department: '技术部'
        },
        {
          employeeId: 5,
          employeeName: '周九',
          phone: '13800138007',
          hireTime: '2024-01-25',
          employeeStatus: 'active',
          position: '测试工程师',
          department: '测试部'
        }
      ],
      3: [
        {
          employeeId: 6,
          employeeName: '郑十一',
          phone: '13800138009',
          hireTime: '2024-01-05',
          employeeStatus: 'active',
          position: '项目经理',
          department: '项目管理部'
        }
      ]
    }
    
    return mockData[enterpriseId] || []
  }
  
  // 刷新数据
  const handleRefresh = async () => {
    try {
      ElMessage.info('正在刷新数据...')
      await loadEmployeeList()
      ElMessage.success('数据刷新成功')
    } catch (error) {
      console.error('刷新数据失败:', error)
      ElMessage.error('刷新数据失败，请重试')
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    loadEmployeeList()
  }
  
  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, {
      keyword: '',
      phone: '',
      status: '',
      hireTimeRange: []
    })
    pagination.current = 1
    loadEmployeeList()
  }
  
  // 添加员工
  const handleAddEmployee = () => {
    console.log('点击添加员工按钮')
    currentEmployee.value = {}
    employeeDialogVisible.value = true
  }
  
  // 编辑员工
  const handleEditEmployee = (employee) => {
    currentEmployee.value = { ...employee }
    employeeDialogVisible.value = true
  }
  
  // 员工操作成功回调
  const handleEmployeeSuccess = (updatedEmployee) => {
    if (updatedEmployee) {
      // 检查是否是更新操作（通过employeeId判断）
      const existingIndex = employeeList.value.findIndex(emp => emp.employeeId === updatedEmployee.employeeId)
      
      if (existingIndex > -1) {
        // 更新现有员工
        employeeList.value[existingIndex] = { ...employeeList.value[existingIndex], ...updatedEmployee }
        console.log('员工信息已更新:', updatedEmployee)
      } else {
        // 添加新员工
        employeeList.value.unshift(updatedEmployee)
        pagination.total++
        console.log('新员工已添加到公司', currentCompanyId.value, ':', updatedEmployee)
      }
    } else {
      // 如果是更新操作但没有返回数据，刷新整个列表
      loadEmployeeList()
    }
    console.log('员工操作成功，刷新列表')
  }
  
  // 查看员工详情
  const handleViewEmployee = (employee) => {
    currentEmployee.value = employee
    detailDialogVisible.value = true
  }
  
  // 切换员工状态
  const handleToggleStatus = async (employee) => {
    const newStatus = employee.employeeStatus === 'active' ? 'inactive' : 'active'
    const action = newStatus === 'active' ? '复职' : '离职'
    
    // 设置弹窗内容
    currentConfirmAction.value = 'toggleStatus'
    currentConfirmEmployee.value = employee
    confirmDialogTitle.value = `${action}员工`
    confirmDialogMessage.value = `确定要${action}员工"${employee.employeeName}"吗？`
    confirmDialogIcon.value = newStatus === 'active' ? 'Check' : 'Warning'
    confirmDialogIconColor.value = newStatus === 'active' ? '#67c23a' : '#e6a23c'
    confirmDialogButtonText.value = `确定${action}`
    confirmDialogButtonType.value = newStatus === 'active' ? 'success' : 'warning'
    confirmDialogVisible.value = true
  }
  
  // 删除员工
  const handleDeleteEmployee = async (employee) => {
    // 设置弹窗内容
    currentConfirmAction.value = 'delete'
    currentConfirmEmployee.value = employee
    confirmDialogTitle.value = '删除员工'
    confirmDialogMessage.value = `确定要删除员工"${employee.employeeName}"吗？此操作不可恢复！`
    confirmDialogIcon.value = 'Delete'
    confirmDialogIconColor.value = '#f56c6c'
    confirmDialogButtonText.value = '确定删除'
    confirmDialogButtonType.value = 'danger'
    confirmDialogVisible.value = true
  }
  
  // 批量删除
  const handleBatchDelete = async () => {
    // 设置弹窗内容
    currentConfirmAction.value = 'batchDelete'
    currentConfirmEmployee.value = selectedEmployees.value
    confirmDialogTitle.value = '批量删除员工'
    confirmDialogMessage.value = `确定要删除选中的 ${selectedEmployees.value.length} 个员工吗？此操作不可恢复！`
    confirmDialogIcon.value = 'Delete'
    confirmDialogIconColor.value = '#f56c6c'
    confirmDialogButtonText.value = '确定删除'
    confirmDialogButtonType.value = 'danger'
    confirmDialogVisible.value = true
  }
  
  // 批量离职
  const handleBatchDeactivate = async () => {
    try {
      await ElMessageBox.confirm(`确定要让选中的 ${selectedEmployees.value.length} 个员工离职吗？`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      // 调用API批量更新员工状态
      await employeeAPI.batchOperateEmployees(selectedEmployees.value.map(emp => emp.employeeId), 'deactivate')
      ElMessage.success('批量离职成功')
      loadEmployeeList()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('批量离职失败')
      }
    }
  }
  
  // 提交员工
  const handleSubmitEmployee = async () => {
    submitting.value = true
    
    try {
      if (isEdit.value) {
        // 这里应该调用API更新员工
        ElMessage.success('员工更新成功')
      } else {
        // 这里应该调用API创建员工
        ElMessage.success('员工添加成功')
      }
      
      employeeDialogVisible.value = false
      loadEmployeeList()
    } catch (error) {
      ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
    } finally {
      submitting.value = false
    }
  }
  
  // 选择变化
  const handleSelectionChange = (selection) => {
    selectedEmployees.value = selection
  }
  
  // 分页大小变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.current = 1
    loadEmployeeList()
  }
  
  // 当前页变化
  const handleCurrentChange = (page) => {
    pagination.current = page
    loadEmployeeList()
  }
  
  // 确认对话框事件处理
  const handleConfirmOk = async () => {
    confirmLoading.value = true
    
    try {
      switch (currentConfirmAction.value) {
        case 'delete':
          // 删除员工
          await employeeAPI.deleteEmployee(currentConfirmEmployee.value.employeeId)
          ElMessage.success('删除成功')
          
          // 从本地列表中移除已删除的员工
          const index = employeeList.value.findIndex(emp => emp.employeeId === currentConfirmEmployee.value.employeeId)
          if (index > -1) {
            employeeList.value.splice(index, 1)
            pagination.total--
          }
          
          // 刷新列表以确保数据同步
          loadEmployeeList()
          break
        case 'batchDelete':
          // 批量删除员工
          const employeeIds = currentConfirmEmployee.value.map(emp => emp.employeeId)
          await employeeAPI.batchOperateEmployees(employeeIds, 'delete')
          ElMessage.success('批量删除成功')
          
          // 从本地列表中移除已删除的员工
          employeeIds.forEach(id => {
            const index = employeeList.value.findIndex(emp => emp.employeeId === id)
            if (index > -1) {
              employeeList.value.splice(index, 1)
              pagination.total--
            }
          })
          
          // 清空选中状态
          selectedEmployees.value = []
          
          // 刷新列表以确保数据同步
          loadEmployeeList()
          break
        case 'toggleStatus':
          // 切换员工状态
          const newStatus = currentConfirmEmployee.value.employeeStatus === 'active' ? 'inactive' : 'active'
          await employeeAPI.updateEmployee(currentConfirmEmployee.value.employeeId, { employeeStatus: newStatus })
          ElMessage.success(`${newStatus === 'active' ? '复职' : '离职'}成功`)
          
          // 更新本地列表中的员工状态
          const employeeIndex = employeeList.value.findIndex(emp => emp.employeeId === currentConfirmEmployee.value.employeeId)
          if (employeeIndex > -1) {
            employeeList.value[employeeIndex].employeeStatus = newStatus
          }
          
          // 刷新列表以确保数据同步
          loadEmployeeList()
          break
        default:
          break
      }
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败，请重试')
    } finally {
      confirmLoading.value = false
      confirmDialogVisible.value = false
    }
  }
  
  const handleConfirmCancel = () => {
    confirmDialogVisible.value = false
    currentConfirmAction.value = ''
    currentConfirmEmployee.value = null
  }
  
  // 对话框关闭
  const handleDialogClose = () => {
    resetEmployeeForm()
    currentEmployee.value = null
  }
  
  // 重置表单
  const resetEmployeeForm = () => {
    Object.assign(employeeForm, {
      employeeName: '',
      phone: '',
      hireTime: '',
      employeeStatus: 'active'
    })
  }
  
  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return ''
    return new Date(dateString).toLocaleDateString('zh-CN')
  }
  
  // 计算工作年限
  const calculateWorkDuration = (hireTime) => {
    if (!hireTime) return '0年'
    const joinDate = new Date(hireTime)
    const now = new Date()
    const diffTime = Math.abs(now - joinDate)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    const years = Math.floor(diffDays / 365)
    const months = Math.floor((diffDays % 365) / 30)
    
    if (years > 0) {
      return months > 0 ? `${years}年${months}个月` : `${years}年`
    } else {
      return months > 0 ? `${months}个月` : '不足1个月'
    }
  }
  
  // 计算工作天数
  const calculateWorkDays = (hireTime) => {
    if (!hireTime) return 0
    const joinDate = new Date(hireTime)
    const now = new Date()
    const diffTime = Math.abs(now - joinDate)
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  }
  
  // 计算工作月数
  const calculateWorkMonths = (hireTime) => {
    if (!hireTime) return 0
    const joinDate = new Date(hireTime)
    const now = new Date()
    const diffTime = Math.abs(now - joinDate)
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 30))
  }
  
  // 计算工作年数
  const calculateWorkYears = (hireTime) => {
    if (!hireTime) return 0
    const joinDate = new Date(hireTime)
    const now = new Date()
    const diffTime = Math.abs(now - joinDate)
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 365))
  }
  </script>
  
  <style scoped>
  .employee-management {
    padding: 20px;
  }
  
  /* 公司切换器样式 */
  .company-switcher {
    margin-bottom: 20px;
  }
  
  /* 确认对话框样式 */
  .confirm-content {
    text-align: center;
    padding: 20px 0;
  }
  
  .confirm-icon {
    margin-bottom: 16px;
  }
  
  .confirm-message {
    font-size: 16px;
    color: #606266;
    line-height: 1.5;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .dialog-footer .el-button {
    margin-left: 10px;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .page-header h2 {
    margin: 0;
    color: #333;
  }
  
  .header-actions {
    display: flex;
    gap: 10px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .employee-list-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-stats {
    flex: 1;
    text-align: center;
  }
  
  .search-result-info {
    color: #666;
    font-size: 14px;
  }
  
  .batch-actions {
    display: flex;
    gap: 10px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .employee-detail {
    padding: 20px 0;
  }
  
  .employee-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
  }
  
  .employee-header h3 {
    margin: 0;
    color: #333;
  }
  
  .employee-info {
    margin-bottom: 20px;
  }
  
  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .info-item label {
    font-weight: 500;
    color: #666;
    min-width: 80px;
    margin-right: 10px;
  }
  
  .info-item span {
    color: #333;
  }
  
  .employee-stats {
    border-top: 1px solid #e0e0e0;
    padding-top: 20px;
  }
  
  .employee-stats h4 {
    color: #333;
    margin-bottom: 15px;
    font-size: 16px;
  }
  
  .stat-item {
    text-align: center;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 4px;
  }
  
  .stat-label {
    display: block;
    color: #666;
    font-size: 14px;
    margin-bottom: 5px;
  }
  
  .stat-value {
    display: block;
    color: #333;
    font-size: 24px;
    font-weight: 600;
  }
  
  /* 操作按钮样式 */
  .action-buttons {
    display: flex;
    flex-wrap: nowrap;
    gap: 4px;
    align-items: center;
  }
  
  .action-buttons .el-button {
    flex-shrink: 0;
    min-width: auto;
    padding: 4px 8px;
    font-size: 12px;
  }
  </style>